<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="httpRequest"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="isShowPer" type="circle" :percentage="percent" />
    </el-upload>
  </div>
</template>
<script>
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDGVcbUGtPjziKoA5taAcxAFC0fCfzBOUp', // 身份识别ID
  SecretKey: 'Hi2FKGMK9rRvdDfzAD7sW5ZxEOSSL8pP' // 身份秘钥
})
export default {
  props: {
    src: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
    //   imageUrl: ''
      imageUrl: this.src,
      isShowPer: false,
      percent: 0
    }
  },
  created() {
    console.log('父组件传递过来的值', this.src)
  },
  methods: {
    httpRequest(res) {
      this.isShowPer = true
      // console.log(val)
      // this.imageUrl = URL.createObjectURL(val.file)
      if (res.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: '13419996210-1315592396', /* 存储桶 */
          Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100
            console.log(this.percent)
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            this.isShowPer = false
            this.imageUrl = `https://${data.Location}`
            this.$emit('upload-success', this.imageUrl)
          }
        })
      }
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
